//
//  HNSH_HomeViewController.m
//  HNSH_SingleProject
//
//  Created by 李宇廷 on 2023/2/16.
//

#import "HNSH_HomeViewController.h"

//view
#import "HNSH_HomeFunctionCell.h"
#import "HNSH_HomeScrollCell.h"
#import "HNSH_HomeGoodsCell.h"
#import "HNSH_HomeGoodsHeader.h"

#import "HNSH_HomeRecommendCell1.h"
#import "HNSH_HomeRecommendCell2.h"

#import "HNSH_HomeNavView.h"
#import "HNSH_NoticeAlert.h"
#import "HNSH_UploadLocalAlert.h"

//vc
#import "HNSH_LoginHomeViewController.h"
#import "HNSH_SearchGoodsViewController.h"
#import "HNSH_GoodsDetailViewController.h"
#import "HNSH_GoodsListViewController.h"

@interface HNSH_HomeViewController ()

/* homeModel */
@property (nonatomic, strong) HNSH_HomeViewModel *homeModel;
/* listAry */
@property (nonatomic, strong) NSMutableArray *listAry;
/* 是否展示公告弹窗 */
@property (nonatomic, assign) BOOL canShowAlert;

/**  */
@property (nonatomic, copy) void(^scrollCallback)(UIScrollView *scrollView);

@end

static NSString *HNSH_HomeScrollCellID = @"HNSH_HomeScrollCellID";
static NSString *HNSH_HomeFunctionCellID = @"HNSH_HomeFunctionCellID";
static NSString *HNSH_HomeRecommendCell1ID = @"HNSH_HomeRecommendCell1ID";
static NSString *HNSH_HomeRecommendCell2ID = @"HNSH_HomeRecommendCell2ID";
static NSString *HNSH_HomeGoodsCellID = @"HNSH_HomeGoodsCellID";
static NSString *HNSH_HomeNullCellID = @"HNSH_HomeNullCellID";

static NSString *HNSH_HomeGoodsHeaderID = @"HNSH_HomeGoodsHeaderID";
static NSString *HNSH_HomeGoodsFooterID = @"HNSH_HomeGoodsFooterID";

@implementation HNSH_HomeViewController

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    if (self.canShowAlert) {
        [self loadHomeMessageAlert];
    }
//    if (![[ST_UserManager shareInstance].user.location isNotBlank] && [ST_UserManager alreadyLogin]) {
//        HNSH_UploadLocalAlert *alert = [[HNSH_UploadLocalAlert alloc]initWithFrame:CGRectMake(0, 0, 300, 204)];
//        [alert showView];
//    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.canShowAlert = YES;
    self.view.backgroundColor = [UIColor appBGColor];
    
    [self configCollectionView];
    
//    [self loadGoodsHomeData];
}

- (void)refreshData:(NSInteger)page {
    [HNSH_ShopNetServer requestGoodsHomeRecommendWithPage_num:page success:^(ST_BaseNetModel * _Nullable responseObject) {
        [self endRefresh:YES];
        if (responseObject.code == 0) {
            if (page == 1) {
                [self.listAry removeAllObjects];
            }
            NSArray *ary = [NSArray yy_modelArrayWithClass:[HNSH_GoodsListModel class] json:responseObject.resultset[@"list"]];
            [self.listAry addObjectsFromArray:ary];
            [self endRefresh:ary.count>=10];
            [self.collectionView reloadData];
        }
    } Failure:^(NSError * _Nullable error) {
        [self endRefresh:YES];
    }];
    
    if (page == 1) {
        [self loadGoodsHomeData];
    }
}

#pragma mark network
- (void)loadGoodsHomeData {
    [HNSH_ShopNetServer requestGoodsHomeDataJXZQSuccess:^(ST_BaseNetModel * _Nullable responseObject) {
        if (responseObject.code == 0) {
            self.homeModel = [HNSH_HomeViewModel yy_modelWithDictionary:responseObject.resultset];
            [self.collectionView reloadData];
        }
    } Failure:^(NSError * _Nullable error) {
        
    }];
}

//首页弹窗
- (void)loadHomeMessageAlert {
    [HNSH_ShopNetServer requestHomeMessageAlertSuccess:^(ST_BaseNetModel * _Nullable responseObject) {
        if (responseObject.code == 0) {
            NSArray *ary = responseObject.resultset;
            if (ary.count > 0) {
                HNSH_NoticeAlertModel *model = [HNSH_NoticeAlertModel yy_modelWithDictionary:ary[0]];
                if ([model.uid isNotBlank]) {
                    [self showHomeAwardAlertWith:model];
                }
            }
        }
    } Failure:^(NSError * _Nullable error) {
        
    }];
}

#pragma mark lazy
- (NSMutableArray *)listAry {
    if (!_listAry) {
        _listAry = [NSMutableArray arrayWithCapacity:0];
    }
    return _listAry;
}

#pragma mark configUI
- (void)configTopView {
    UIImageView *imgV = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kNavBarAndStatusBarHeight+174)];
    imgV.image = [UIImage imageNamed:@"home_top_bg"];
    [self.view addSubview:imgV];
    [self.view sendSubviewToBack:imgV];
}

- (void)configNav {
    HNSH_HomeNavView *nav = [[HNSH_HomeNavView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kNavBarAndStatusBarHeight)];
    WeakSelf(weakSelf);
    nav.searchBlock = ^{
        HNSH_SearchGoodsViewController *vc = [[HNSH_SearchGoodsViewController alloc]init];
        [weakSelf.navigationController pushViewController:vc animated:YES];
    };
    [self.view addSubview:nav];
}

#pragma mark 弹窗
- (void)showHomeAwardAlertWith:(HNSH_NoticeAlertModel *)model {
    self.canShowAlert = NO;
    HNSH_NoticeAlert *alert = [[HNSH_NoticeAlert alloc]init];
    alert.backgroundColor = [UIColor whiteColor];
    alert.model = model;
    __weak __typeof(&*self)weakSelf = self;
    alert.showBlock = ^{
        weakSelf.canShowAlert = YES;
        [NSString jumpToolsWithJumpType:model.jump_type jump_name:model.title jump_content:model.jump_content jump_params:model.jump_params];
    };
    [alert showViewWithView:kSTWindow];
}

- (void)configCollectionView {
    self.collectionView.backgroundColor = [UIColor clearColor];
    //添加刷新
    [self setupRefresh:self.collectionView option:ST_RefreshDefault];
    //添加空页面
    [self setupEmpty:self.collectionView image:[UIImage imageNamed:@"empty_list_data"] title:@""];
    
    [self.collectionView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(UIEdgeInsetsMake(0, 0, kTabBarHeight, 0));
    }];
    
    [self.collectionView registerClass:[HNSH_HomeScrollCell class] forCellWithReuseIdentifier:HNSH_HomeScrollCellID];
    [self.collectionView registerClass:[HNSH_HomeFunctionCell class] forCellWithReuseIdentifier:HNSH_HomeFunctionCellID];
    [self.collectionView registerClass:[HNSH_HomeRecommendCell1 class] forCellWithReuseIdentifier:HNSH_HomeRecommendCell1ID];
    [self.collectionView registerClass:[HNSH_HomeRecommendCell2 class] forCellWithReuseIdentifier:HNSH_HomeRecommendCell2ID];
    [self.collectionView registerClass:[HNSH_HomeGoodsCell class] forCellWithReuseIdentifier:HNSH_HomeGoodsCellID];
    [self.collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:HNSH_HomeNullCellID];
    
    [self.collectionView registerClass:[HNSH_HomeGoodsHeader class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:HNSH_HomeGoodsHeaderID];
    [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:HNSH_HomeGoodsFooterID];
}

#pragma mark UICollectionViewDataSource
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 6;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (section == 5) {
        return self.listAry.count;
    }
    if (section == 1) {
        if (![[NSUserDefaults standardUserDefaults] boolForKey:KUserShowHiddenContentID]) {
            return 0;
        }
    }
    if (section == 2) {
        if (!([[NSUserDefaults standardUserDefaults] boolForKey:KUserShowHiddenContentID] && self.homeModel.hdzq_list && self.homeModel.hdzq_list.count > 0)) {
            return 0;
        }
    }
    return 1;
}
//设置海报图片
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        HNSH_HomeFunctionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:HNSH_HomeFunctionCellID forIndexPath:indexPath];
        cell.model = self.homeModel;
        return cell;
    } else if (indexPath.section == 1) {
        if ([[NSUserDefaults standardUserDefaults] boolForKey:KUserShowHiddenContentID]) {
            HNSH_HomeScrollCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:HNSH_HomeScrollCellID forIndexPath:indexPath];
            cell.model = self.homeModel;
            return cell;
        }
        UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:HNSH_HomeNullCellID forIndexPath:indexPath];
        return cell;
    } else if (indexPath.section == 2) {
        if ([[NSUserDefaults standardUserDefaults] boolForKey:KUserShowHiddenContentID] && self.homeModel.hdzq_list && self.homeModel.hdzq_list.count > 0) {
            HNSH_HomeScrollCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:HNSH_HomeScrollCellID forIndexPath:indexPath];
            cell.activeModel = self.homeModel;
            return cell;
        }
        UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:HNSH_HomeNullCellID forIndexPath:indexPath];
        return cell;
    } else if (indexPath.section == 3) {
        HNSH_HomeRecommendCell1 *cell = [collectionView dequeueReusableCellWithReuseIdentifier:HNSH_HomeRecommendCell1ID forIndexPath:indexPath];
        cell.model = self.homeModel;
        return cell;
    } else if (indexPath.section == 4) {
        HNSH_HomeRecommendCell2 *cell = [collectionView dequeueReusableCellWithReuseIdentifier:HNSH_HomeRecommendCell2ID forIndexPath:indexPath];
        cell.model = self.homeModel;
        return cell;
    } else if (indexPath.section == 5) {
        HNSH_HomeGoodsCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:HNSH_HomeGoodsCellID forIndexPath:indexPath];
        cell.model = self.listAry[indexPath.row];
        return cell;
    }
    return nil;
}
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 5 && kind == UICollectionElementKindSectionHeader) {
        HNSH_HomeGoodsHeader * header = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:HNSH_HomeGoodsHeaderID forIndexPath:indexPath];
        header.iconImgV.image = [UIImage imageNamed:@"home_goods_header_icon"];
        header.titleLabel.text = @"精品推荐";
        WeakSelf(weakSelf);
        header.clickBlock = ^{
            HNSH_GoodsListViewController *vc = [[HNSH_GoodsListViewController alloc]init];
            vc.type = @"1";
            [weakSelf.navigationController pushViewController:vc animated:YES];
        };
        return header;
    }
    
    UICollectionReusableView * reusableView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:HNSH_HomeGoodsFooterID forIndexPath:indexPath];
    if (indexPath.section == 0 || indexPath.section == 1) {
        reusableView.backgroundColor = [UIColor clearColor];
    } else {
        reusableView.backgroundColor = [UIColor clearColor];
    }
    return reusableView;
}
#pragma mark UICollectionViewDelegateFlowLayout
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    if (section == 5) {
        return UIEdgeInsetsMake(0, 12, 8, 12);
    }
    return UIEdgeInsetsZero;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return CGSizeMake(kScreenWidth, 174);
    } else if (indexPath.section == 1) {
        if ([[NSUserDefaults standardUserDefaults] boolForKey:KUserShowHiddenContentID]) {
            return CGSizeMake(kScreenWidth, 88);
        }
        return CGSizeZero;
    } else if (indexPath.section == 2) {
        if ([[NSUserDefaults standardUserDefaults] boolForKey:KUserShowHiddenContentID] && self.homeModel.hdzq_list && self.homeModel.hdzq_list.count > 0) {
            return CGSizeMake(kScreenWidth, 88);
        }
        return CGSizeZero;
    } else if (indexPath.section == 3) {
        return CGSizeMake(kScreenWidth, 172);
    } else if (indexPath.section == 4) {
        return CGSizeMake(kScreenWidth, 138);
    } else if (indexPath.section == 5) {
        CGFloat width = (kScreenWidth-32)/2;
        return CGSizeMake(width, width+91);
    }
    return CGSizeZero;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    if (section == 5) {
        return 8;
    }
    return 0;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    if (section == 5) {
        return 8;
    }
    return 0;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    if (section == 5) {
        return CGSizeMake(kScreenWidth, 48);
    }
    if (section == 1) {
        if ([[NSUserDefaults standardUserDefaults] boolForKey:KUserShowHiddenContentID]) {
            return CGSizeMake(kScreenWidth, 16);
        } else {
            return CGSizeMake(kScreenWidth, 0);
        }
    }
    if (section == 2) {
        if ([[NSUserDefaults standardUserDefaults] boolForKey:KUserShowHiddenContentID] && self.homeModel.hdzq_list && self.homeModel.hdzq_list.count > 0) {
            return CGSizeMake(kScreenWidth, 16);
        } else {
            return CGSizeMake(kScreenWidth, 0);
        }
    }
    return CGSizeMake(kScreenWidth, 10);
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section{
    return CGSizeZero;
}
#pragma mark UICollectionViewDataSource
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    [collectionView deselectItemAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 5) {
        HNSH_GoodsListModel *model = self.listAry[indexPath.row];
        HNSH_GoodsDetailViewController *vc = [[HNSH_GoodsDetailViewController alloc]init];
        vc.goodsId = model.uid;
        [self.navigationController pushViewController:vc animated:YES];
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    !self.scrollCallback ?: self.scrollCallback(scrollView);
}

//MARK: JXPagingViewListViewDelegate Methods
- (UIView *)listView{
    return self.view;
}

- (UIScrollView *)listScrollView{
    return self.collectionView;
}

- (void)listViewDidScrollCallback:(void (^)(UIScrollView *))callback{
    self.scrollCallback = callback;
}

- (void)listWillAppear{
    NSLog(@"%@:%@", self.title, NSStringFromSelector(_cmd));
}

- (void)listDidAppear{
    NSLog(@"%@:%@", self.title, NSStringFromSelector(_cmd));
}

- (void)listWillDisappear{
    NSLog(@"%@:%@", self.title, NSStringFromSelector(_cmd));
}

- (void)listDidDisappear{
    NSLog(@"%@:%@", self.title, NSStringFromSelector(_cmd));
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
